import { useRef, useEffect } from 'react';
import { Modal, Form, Button } from 'antd';
import _ from 'lodash';
import Abstract from '../components/Abstract';
import MessageTempSelector from '../components/MessageTempSelector';
import './style.less';

export default function MessageTemplate(props: any) {
    const { modalParams, title, value, onChange, controlData } = props;
    const [form] = Form.useForm();
    const tempRef = useRef<any>();

    const onCancel = () => {
        modalParams?.onCancel && modalParams?.onCancel();
    };

    const onSave = () => {
        form.validateFields().then((res) => {
            onChange({
                ifPush: true,
                template: res,
            });
            onCancel();
        }).catch((error) => {
            const errorFields = error?.errorFields;
            const ifFieldsError = errorFields?.length > 0 ? errorFields?.some((item: { name: string[]; }) => item?.name?.includes('fields')) : false;
            if (ifFieldsError) {
                tempRef?.current?.setIfformItemError(true);
            }
        })
    };

    const onValuesChange = (_: any, values: any) => {
        if (!values?.template) {
            tempRef?.current?.setIfformItemError(true);
        } else {
            tempRef?.current?.setIfformItemError(false);
        }
    };

    useEffect(() => {
        form.setFieldsValue({
            template: value?.template?.template || null,
            fields: (_.isEmpty(value?.template?.fields) || !value?.template?.fields) ? [] : value?.template?.fields,
        })
    }, [value]);

    return (
        <Modal
            {...modalParams}
            title={title}
            bodyStyle={{
                padding: '10px 20px 20px',
                overflow: 'auto',
            }}
        >
            <Form
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 16 }}
                labelAlign='right'
                labelWrap={true}
                layout={'horizontal'}
                form={form}
                onValuesChange={onValuesChange}
            >
                <Form.Item label='消息模板' name='template' rules={[{ required: true, message: '请选择消息模板' }]}>
                    <MessageTempSelector ref={tempRef} />
                </Form.Item>
                <Form.Item label='消息参数' name='fields' >
                    <Abstract controlData={controlData} />
                </Form.Item>
            </Form>
            <div className='process-designer-message-template-footer'>
                <Button type='primary' onClick={onSave}>确定</Button>
                <Button onClick={onCancel}>取消</Button>
            </div>
        </Modal>
    );
};